package com.alliky.user.ui.viewmodel;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;

import com.alliky.core.base.viewmodel.ToolbarViewModel;
import com.alliky.core.binding.command.BindingCommand;
import com.alliky.core.bus.RxBus;
import com.alliky.core.bus.RxMessager;
import com.alliky.core.bus.SingleLiveEvent;
import com.alliky.core.contract._Login;
import com.alliky.core.data.DataRepository;
import com.alliky.core.entity.vo.UserVO;
import com.alliky.core.global.Global;
import com.alliky.core.net.IDisposableObserver;
import com.alliky.core.util.RxToast;
import com.alliky.core.util.RxUtils;
import com.blankj.utilcode.util.ObjectUtils;

import java.util.WeakHashMap;

/**
 * @Description TODO
 * @Author wxianing
 * @Date 2020-11-15
 */
public class LoginViewModel extends ToolbarViewModel<DataRepository> {
    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>("");
    //密码的绑定
    public ObservableField<String> password = new ObservableField<>("");
    //用户名清除按钮的显示隐藏绑定
    public ObservableInt clearBtnVisibility = new ObservableInt();
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Boolean> pSwitchEvent = new SingleLiveEvent<>();

        //监听数据源
        public SingleLiveEvent<UserVO> mUserVOSingleLiveEvent = new SingleLiveEvent<>();
    }

    public LoginViewModel(@NonNull Application application) {
        super(application);
        setTitleText("登录");
    }

    //清除用户名的点击事件, 逻辑从View层转换到ViewModel层
    public BindingCommand clearUserNameOnClickCommand = new BindingCommand(() -> userName.set(""));
    //密码显示开关  (你可以尝试着狂按这个按钮,会发现它有防多次点击的功能)
    public BindingCommand passwordShowSwitchOnClickCommand = new BindingCommand(() -> {
        //让观察者的数据改变,逻辑从ViewModel层转到View层，在View层的监听则会被调用
        uc.pSwitchEvent.setValue(uc.pSwitchEvent.getValue() == null || !uc.pSwitchEvent.getValue());
    });
    //用户名输入框焦点改变的回调事件
    public BindingCommand<Boolean> onFocusChangeCommand = new BindingCommand<>(hasFocus -> {
        if (hasFocus) {
            clearBtnVisibility.set(View.VISIBLE);
        } else {
            clearBtnVisibility.set(View.INVISIBLE);
        }
    });
    //登录按钮的点击事件
    public BindingCommand loginOnClickCommand = new BindingCommand(() -> login());

    /**
     * 网络模拟一个登陆操作
     **/
    private void login() {
        if (TextUtils.isEmpty(userName.get())) {
            RxToast.normal("请输入账号！");
            return;
        }
        if (TextUtils.isEmpty(password.get())) {
            RxToast.normal("请输入密码！");
            return;
        }

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("username", userName.get());
        params.put("password", password.get());

        mRepository.doLogin(params)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))// 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())// 线程调度
                .compose(RxUtils.exceptionTransformer())// 网络错误的异常转换
                .doOnSubscribe(this)
                .subscribe(new IDisposableObserver<UserVO>(this, "正在登录") {
                    @Override
                    protected void onResult(UserVO userVO) {
                        if (ObjectUtils.isNotEmpty(userVO)) {
                            _Login _login = new _Login();
                            //采用ARouter+RxBus实现组件间通信
                            RxBus.getDefault().post(_login);
                            uc.mUserVOSingleLiveEvent.postValue(userVO);

                            Global.UserManage.saveToken(userVO.getToken());
                            Global.UserManage.saveUser(userVO);

                            RxMessager.getDefault().send("登录成功", MyViewModel.KEY_LOGIN_SUCCESS);
                            //关闭页面
                            finish();
                        }
                    }
                });
    }
}
